package src.unapec.seguridad.ejemplos.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Key {

	SecretKey key = null;
	String path = "/home/rmatos/Desktop/key.config";
	String otherPath = "/home/rmatos/Desktop/other.config";
		
	public void createOtherKey(byte[] keyBytes , String keyType){
		
		 //byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
		 //0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };

		 //keyType = "AES"
	
	try{
		
		key = new SecretKeySpec(keyBytes, keyType);
		
		File file = new File(otherPath);
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
		
		oos.writeObject(key);
		oos.close();
	
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
		
		
	}
		
	public void createNewDESKey(){
		
		try {
			
			key = KeyGenerator.getInstance("DES").generateKey();
			
			File file = new File(path);
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
			
			oos.writeObject(key);
			oos.close();
		
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}
		
	public SecretKey getKeys(int type){

		File file = null;
		
		if(type == 1){
			
			file = new File(path);

			
		}else{
			
			file = new File(otherPath);
			
		}
		
		
		try {
			
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
			
			key = (SecretKey)ois.readObject();
	
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		return key;
		
	}
	
}
